<template>
  <div class="parent" @keyup.delete="showDelete">
    <div id="map">
    </div>
    <el-dialog
      custom-class="mDialog"
      title="信息编辑"
      :visible.sync="dialogVisible"
      width="80%"
      append-to-body
    >
      <span>
        <el-table
          :data="features"
          style="width: 100%">
           <el-table-column
             type="index"
             width="50">
    </el-table-column>
      <el-table-column
        prop="date"
        label="地块名称"
      >        <template slot="header" slot-scope="scope">
        <span style="color: red">* </span><span>地块名称</span>
      </template>

         <template slot-scope="scope">
          <el-input v-model="scope.row.properties.dkmc" size="small" clearable style="width: 100px"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="地块编码"
      > <template slot="header" slot-scope="scope">
        <span style="color: red">* </span><span>地块编码</span>
      </template>
        <template slot-scope="scope">
          <el-input v-model="scope.row.properties.dkbm" size="small" clearable style="width: 150px"></el-input>
        </template>
      </el-table-column><el-table-column
          prop="name"
          label="村名称"
        > <template slot-scope="scope">

          <el-cascader size="small" clearable style="width: 150px" :show-all-levels="false" :props="props"
                       v-model="scope.row.properties.all"
                       :placeholder="scope.row.properties.village_na||''"
                       :options="areaOptions"
                       class="areaInput"
                       @change="selectArea($event,scope.row)"
          ></el-cascader>
        </template>
      </el-table-column><el-table-column
          prop="name"
          label="村代码"
        > <template slot-scope="scope">
          <el-input v-model="scope.row.properties.village_cd" size="small" clearable style="width: 150px"
                    ></el-input>
        </template>
      </el-table-column>
<!--          <el-table-column-->
<!--          prop="name"-->
<!--          label="海拔高度"-->
<!--        > <template slot-scope="scope">-->
<!--            <el-input-number :controls="false" v-model="scope.row.properties.altitude" :precision="2" :step="0.1"-->
<!--                             clearable style="width: 150px"></el-input-number>-->
<!--        </template>-->
<!--      </el-table-column>-->
 <el-table-column
   prop="name"
   label="面积"
 > <template slot-scope="scope">
   <span>
     {{ scope.row.properties.shape_area|unitToMu }}
   </span>
        </template>
      </el-table-column>
    </el-table>

      </span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="clear">取 消</el-button>
    <el-button type="primary" @click="submitData">提 交</el-button>
  </span>
    </el-dialog>
    <edit-group @splitCallBack="splitCallBack"
                :selectFeatures="features"
                @submitGraffiti="submitGraffiti"
                @error="error"
                @union="union"
                :map="map"
                :stateManager="stateManager"
                @addSelectDK="addFeatures"
                @deleteSelect="showDelete"
                @addCallBack="showDialog"
                :curFun="curFun"></edit-group>
    <!--    <tool-group  :map="map" :stateManager="stateManager" @clear="clear"></tool-group>-->
    <left-top :qhdm="qhdm" :dkInfo="newPathData" @activeMapLocation="getTolocation"></left-top>
    <layer-control :map="map" :iszzjg="false" v-if="ready"></layer-control>
    <!--地图级别-->
    <div class="zoom-info">
      <div><span>级别：{{ curLevel }}</span></div>
      <div><span>经度：{{ curLng }}</span></div>
      <div><span>纬度：{{ curLat }}</span></div>
      <div><span>当前：{{ curAreaName }}</span></div>
    </div>
  </div>
</template>

<script>
import mapboxgl from "mapbox-gl";

import EditGroup from "./EditGroup";
import ToolGroup from "./ToolGroup";
import LeftTop from "./LeftTop";
import LayerControl from "./LayerControl";
import StateManager from "./StateManager"
import api_map from "../../api/api_map";
import Turf from "turf";
import SelectPolygon from "../../model/SelectPolygon";
import MapCommon from "../../common/MapCommon";
import _ from "lodash"
import layer_identify from "../../common/layer_identify";
import TempLayer from "../../model/TempLayer";
import * as turfInvariant from '@turf/invariant';
import api_dock from "../../api/api_dock";
import WKT from "terraformer-wkt-parser"


export default {
  name: "Map",
  components: { EditGroup, ToolGroup, LeftTop, LayerControl},
  created() {

  },
  mounted() {
    this.initMap();
    api_dock.getArea().then(res => {
      let array = [];
      let data = JSON.parse(res.data)
      for (let i = 0; i < data.resultObject.length; i++) {
        let item = data.resultObject[i];
        let result = {
          all:{value: item.divisionUniqueCd,
            label: item.divisionName},
          value: item.divisionUniqueCd,
          label: item.divisionName,
          children: []
        }
        array.push(result)
      }

      this.areaOptions = array;

    }).catch(err => {
      console.error(err)
    })
  },
  data() {
    return {
      areaOptions: [],
      redIcon: "url(" + require("../../../static/img/gre.png") + ")",
      rediconMarkers: [],
      infoMarkers: [],
      featureArr: [],
      a: undefined,
      b: undefined,
      oneInfoShape: undefined,
      newPathData: {},
      map: null,
      ready: false,
      curFun: "",//当前功能
      stateManager: null,
      qhmc: "",
      qhdm: "",
      xmbm: "",
      idcode: "",
      name: "",
      nf: "",
      zytype: "",
      features: [],
      mjLimit: 50,
      curLevel: 6,
      curLng: 113.613296188474,
      curLat: 33.8824613831615,
      curAreaName: "河南省",
      dialogVisible: false,
      needDelete: [],
      needDeleteFeatures: [],
      testValue: [],
      props:{
        value: 'all',
        label: 'label',
        emitPath:false,
        lazy: true,
        lazyLoad (node, resolve) {
          const { level,data } = node;
            console.log(node)
          let param={};
            if(level>0){
              param.orgUniqueCd=data.value
            }
            api_dock.getArea(param).then(res => {
              let array = [];
              let data = JSON.parse(res.data)
              for (let i = 0; i < data.resultObject.length; i++) {
                let item = data.resultObject[i];
                let result = {
                  all:{value: item.divisionUniqueCd,
                    label: item.divisionName},
                  value: item.divisionUniqueCd,
                  label: item.divisionName,
                  leaf: level >= 2
                }
                array.push(result)
              }
              resolve(array);
            }).catch(err => {
              console.error(err)
            })
        }
      }
    }
  },
  filters:{
    unitToMu(value){
      return (value*0.0015).toFixed(2)+"亩"
    }
  },
  methods: {
    array2Tree(arr){
      if(!Array.isArray(arr) || !arr.length) return;
      let map = {};
      arr.forEach(item => map[item.id] = item);

      let roots = [];
      arr.forEach(item => {
        const parent = map[item.parentId];
        if(parent){
          (parent.children || (parent.children=[])).push(item);
        }
        else{
          roots.push(item);
        }
      })

      return roots;
    },
    selectArea(val, row) {
      row.properties.village_na = val.label;
      api_map.getNextValue().then(res=>{
        let num=res.data+"";
        if(num.length<7){
          for (let i = num.length; i <= 7; i++) {
            num="0"+num;
          }
        }
        num=val.value+""+num;
        this.$set( row.properties, "dkbm", num )
        this.$set( row.properties, "village_cd", val.value )
        // row.properties.dkbm = num;
      }).catch(err=>{
        console.error(err)
      })
    },
    showDelete() {
      if (this.features.length === 0) {
        return
      }
      this.$alert('确定要删除选中地块吗？', '提示', {
        confirmButtonText: '确定',
        showCancelButton: true,
        callback: action => {
          if (action === "confirm")
            this.deleteDk();
        }
      });
    },

    async deleteDk() {

      if (this.stateManager.getCurrentFunId() === "SelectPolygon") {
        let loading = this.$loading({
          lock: true,
          text: '删除中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        if (this.features.length > 0) {
          if(!await this.batchDeleteDkSimple(this.features)){
            loading.close()
            return
          }
        }
        loading.close()
        this.features = [];
        this.stateManager.removeCurrent();
        this.$bus.emit("refreshDkList");
      } else {
        this.$message.error('当前模式无法删除');
      }

    },

    getNowDate() {
      let date = new Date();
      let sign1 = "-";
      let sign2 = ":";
      let year = date.getFullYear() // 年
      let month = date.getMonth() + 1; // 月
      let day = date.getDate(); // 日
      let hour = date.getHours(); // 时
      let minutes = date.getMinutes(); // 分
      let seconds = date.getSeconds() //秒
      // 给一位数数据前面加 “0”
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (day >= 0 && day <= 9) {
        day = "0" + day;
      }
      if (hour >= 0 && hour <= 9) {
        hour = "0" + hour;
      }
      if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
      }
      if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
      }
      let currentdate = year + sign1 + month + sign1 + day + " " + hour + sign2 + minutes + sign2 + seconds;
      return currentdate;
    },

    getMj(value){
      if(!value){
        return 0.00
      }
      return  (value*0.0015).toFixed(2)
    },
    //上传删除信息
    async uploadFeaturesDel(features) {
      debugger
      let date=this.getNowDate();
      let params = features.map(item => {
        return {
          "actionType": "del",
          "fieldId": item.properties.dkbm,
          "fieldLon": item.properties.lng,
          "fieldLat": item.properties.lat,
          "fieldAlt": item.properties.altitude||0,
          "fieldArea": item.properties.dkmj*666.67,
          "fieldVillage": item.properties.village_cd,
          "fieldPoint": "undefined",
          "fieldToponym": "undefined",
          "fieldName": "                    ",
          "fieldYear": "0         ",
          "fieldInputtime": date,
          "fieldInputname": item.properties.dkmc,
          "fieldInputcunname": item.properties.village_na,
          "fieldState": 0,
          "fieldRevisetime": null,
          "fieldRevisename": null,
          "fieldShpway": null,
          "fieldShp":  WKT.convert(item.geometry).replaceAll(", ",",").replaceAll(" (","("),
          "dbName": "shp_es_enshi"
        }
      })
      let res=await api_dock.uploadInfo(params);
      if(res.data){
        let result=JSON.parse(res.data).resultObject
        if(result["true"]){
          return true
        }else {
          for (let i = 0; i < result["false"].length; i++) {
            this.$message.error(result["false"][i].remark);
          }
          return false
        }
      }else{
        this.$message.error("删除校验失败"+res)
      }
      return false
    },
//上传删除信息
    async uploadFeaturesAddOrUpdate(features) {
      let date=this.getNowDate();
      let params = features.map(item => {
        return {
          "actionType": item.properties.objectid?"update":"add",
          "fieldId": item.properties.dkbm,
          "fieldLon": item.properties.lng,
          "fieldLat": item.properties.lat,
          "fieldAlt": item.properties.altitude||0,
          "fieldArea": item.properties.dkmj*666.67,
          "fieldVillage": item.properties.village_cd,
          "fieldPoint": "undefined",
          "fieldToponym": "undefined",
          "fieldName": "                    ",
          "fieldYear": "0         ",
          "fieldInputtime": date,
          "fieldInputname": item.properties.dkmc,
          "fieldInputcunname": item.properties.village_na,
          "fieldState": 0,
          "fieldRevisetime": null,
          "fieldRevisename": null,
          "fieldShpway": null,
          "fieldShp": WKT.convert(item.geometry).replaceAll(", ",",").replaceAll(" (","("),
          "dbName": "shp_es_enshi"
        }
      })
      let res=await api_dock.uploadInfo(params)
      if(res.data){
        let result=JSON.parse(res.data).resultObject
        if(result["true"]){
          return true
        }else {
          for (let i = 0; i < result["false"].length; i++) {
            this.$message.error(result["false"][i].remark);
          }
          return false
        }
      }

      return false
    },
    //仅仅删除地块
    async batchDeleteDkSimple(features, showSuccess = true) {
      let ids = features.map(feature => {
        return feature.properties.objectid
      })
      let temp=this.uploadFeaturesDel(features);
      if(!temp){
        return false
      }
      let res = await api_map.batchDeleteDk(ids);
      if (!res || res.code != 0) {
        this.$message.error('删除地块失败');
      } else if (showSuccess) {
        this.$message({
          message: '删除成功',
          type: 'success'
        });
      }
      return true;
    },
    //仅仅删除地块
     async batchDeleteDkSimpleAsync() {
      if (!this.needDelete || this.needDelete.length === 0) {
        return true
      }
       return await this.uploadFeaturesDel(this.needDeleteFeatures);
    },
    clear() {
      this.dialogVisible = false;
      this.features = [];
      this.tempLayer.clearFeatures();
      //移除定位效果
      if (this.map.getLayer("drawLine")) {
        this.map.removeLayer("drawLine")
      }
      if (this.map.getSource("drawLine")) {
        this.map.removeSource("drawLine")
      }
      this.stateManager.removeCurrent();
    },
    /**
     * 分割回调
     * */
    async splitCallBack(result) {
      console.log("分割回调")
      //防止重复触发
      if (this.features.length === 0) {
        return
      }
      if (!result.msg) {
        if (this.features[0].properties.myobjectid) {
          this.needDelete = [this.features[0].properties.objectid]
          this.features[0].properties.objectid=null;
          this.needDeleteFeatures = [JSON.parse(JSON.stringify(this.features[0]))]
          this.features = [];
          this.showDialog(result.features);
          return;
        }
        this.features = [];
        let features = result.features;
        for (let i = 0; i < features.length; i++) {
          features[i].myobjectid = features[i].myobjectid + "_" + i;
          features[i].properties.objectid =null;
        }

        this.tempLayer.addFeatures(features);
      } else {
        this.error(result.msg)
      }
    },
    async submitData() {
      let dkbmsSet = new Set();

      for (let i = 0; i < this.features.length; i++) {
        let feature = this.features[i];
        if (!feature.properties.dkbm) {
          this.$message.error("请输入地块编码!");
          return
        }
        if (!feature.properties.dkmc) {
          this.$message.error("请输入地块名称!");
          return
        }
        dkbmsSet.add(feature.properties.dkbm);
      }
      if (dkbmsSet.size !== this.features.length) {
        this.$message.error("地块编码不能重复!");
        return
      }

      for (let i = 0; i < this.features.length; i++) {
        let feature = this.features[i];

        if (this.getMj(Turf.area(feature)) > this.mjLimit) {
          this.$message.error('地块面积不能超过50亩');
          return;
        }


      }



      let temp=await this.batchDeleteDkSimpleAsync();
      if(!temp){
        return
      }
      await this.addCallBack(this.features)
      this.dialogVisible = false;

    },
    showDialog(features) {
      for (let i = 0; i < features.length; i++) {
        let center = Turf.center(features[i]);
        console.log(center.geometry.coordinates)
        features[i].properties.shape_area = Turf.area(features[i]).toFixed(2);
        // features[i].properties.shape_leng = Turf.length(features[i],{units: 'kilometers'}).toFixed(2);
        features[i].properties.lat = center.geometry.coordinates[1].toFixed(6);
        features[i].properties.lng = center.geometry.coordinates[0].toFixed(6);
        features[i].properties.dkmj = this.getMj(features[i].properties.shape_area);

        features[i].properties.altitude = features[i].properties.altitude||0;
      }
      this.dialogVisible = true;
      this.features = features
    },
    /**
     * 提交涂鸦
     */
    submitGraffiti(feature) {
      this.showDialog([feature])
    },
    async addCallBack(features) {
      if (!features || features.length === 0) {
        this.$message.error("请选择待添加地块!");
        return
      }
      for (let i = 0; i < features.length; i++) {
        let feature = features[i];

        if (this.getMj(Turf.area(feature)) > this.mjLimit) {
          this.$message.error('绘制范围过大');
          return;
        }

        //点和线检测
        let type = turfInvariant.getType(feature);
        if (type == "Point" || type == "LineString") {
          this.error('不允许提交点和线');
          return;
        }
        feature.properties.shape_area = Turf.area(feature).toFixed(2);
      }

      let loading = this.$loading({
        lock: true,
        text: '上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let temp=await this.uploadFeaturesAddOrUpdate(features);
      if(  temp ){
        api_map.addAndDeleteShape({
          addFeature:{
            carriesFeatureList: [
              {
                carries: {
                  ytdk0305: features
                }
              }
            ]
          },
          ids: this.needDelete
        }).then(res => {
          if (res.code !== 0) {
            this.$message.error('新增失败' + res.msg);
          } else {
            this.needDelete = [];
            this.needDeleteFeatures = [];
            this.tempLayer.clearFeatures();
            this.$bus.emit("refreshDkList");
          }
        }).catch(error => {
          console.error(error);
          this.$message.error('新增失败');
        }).finally(() => {
          this.stateManager.removeCurrent();
          loading.close();
          this.features = [];
        })
      }else{
        loading.close();
      }



    },
    initMap() {
      let that = this;
      let map = new mapboxgl.Map({
        container: "map",
        style: process.env.MAPID,
        maxZoom: 20,
        dragRotate: false,
        pitchWithRotate: false,
        touchZoomRotate: true,
        refreshExpiredTiles: true,
      });
      this.map = map;
      //解决canvas渲染不正确
      map.on("styledata", function () {
        map.resize();
      });
      map.on("load", (e) => {
        //禁止旋转
        map.touchZoomRotate.disableRotation();
        map.dragRotate.disable();
        this.ready = true;
        this.tempLayer = new TempLayer(map);
        this.stateManager = new StateManager(this.modeChange, this.funMaker);
        // this.stateManager = new StateManager(this.modeChange);
        console.log("地图已加载");


        for (let i = 0; i < layer_identify.layer_Drilldown.length; i++) {
          let lyrDrl = layer_identify.layer_Drilldown[i];
          //1增加透明的fill图层用于查询
          if (!map.getLayer(lyrDrl.layer_fill + "_search")) {
            map.addLayer({
              id: lyrDrl.layer_fill + "_search",
              type: "fill",
              source: lyrDrl.sourceId,
              "source-layer": lyrDrl.sourceLayer,
              minzoom: lyrDrl.minzoom,
              maxzoom: lyrDrl.maxzoom,
              layout: {},
              paint: {
                "fill-opacity": 0.0,
              },
            });
          } else {
            /*add by gf 20190123  由于定制地图将这些用于查询的图层visibility设置为隐藏，不能做查询，这里在用到的时候将visibility设置为可见 */
            map.setLayoutProperty(
              lyrDrl.layer_fill + "_search",
              "visibility",
              "visible"
            );
          }
        }

        //如果有this.a，可以控制不走calCenterAdminArea

        if (that.oneInfoShape) {
          that.location(that.oneInfoShape.shape1)
        }
        if (that.yzInfo) {
          this.getYzInfo(that.yzInfo)
        }

        this.calCenterAdminArea();

      });
      //实时级别、中心点
      map.on('drag', this.mapDrag);
      map.on('zoomend', this.mapZoomEnd);
      map.on('moveend', this.mapMoveEnd);
    },
    funMaker() {
      let clickLayersFilters = [
        {
          layer: "养殖地块",
          key: "zytype",
          value: "03"
        }, {
          layer: "种植地块",
          key: "zytype",
          value: "03"
        },
      ];
      let selectLayers = [this.tempLayer.layerName, "烟田地块-边界"];

      return new SelectPolygon(this.map, {
        clickLayers: selectLayers, callBack: this.selectChange, features: this.features,
        clickLayersFilters: clickLayersFilters
      })
    },
    addFeatures() {
      this.showDialog(this.features)
    },
    selectChange(set) {
      this.features = set.features;
    },
    modeChange(e) {
      this.curFun = e;
    },


    union() {
      if (this.features && this.features.length >= 2) {
        let ids = [];
        let sources = [];
        for (let i = 0; i < this.features.length; i++) {
          if (this.features[i].layer && this.features[i].layer.id && ids.indexOf(this.features[i].layer.id) < 0) {
            ids.push(this.features[i].layer.id);
            sources.push(this.features[i].source)
          }
        }
        if (ids.length > 1) {
          this.error("不同类别地块禁止合并！");
          return
        }

        let res = MapCommon.unionPolygons(this.features);
        if (res.msg) {
          this.error(res.msg);
        } else {
          this.needDelete = [];
          this.needDeleteFeatures = [];
          res.polygon.properties.objectid=null;
          for (let i = 0; i < this.features.length; i++) {
            let feature = this.features[i];
            if (feature.properties.objectid) {
              this.needDelete.push(feature.properties.objectid)
              this.needDeleteFeatures.push(JSON.parse(JSON.stringify(feature)))
            }
          }
          this.showDialog([res.polygon])
        }
      } else {
        this.$message.error('请选择两个以上地块');
      }
    },

    error(msg) {
      this.$message.error(msg);
    },
    location(val) {
      val = JSON.parse(val);
      let feature = Turf.feature(val);
      console.log(feature)
      let bbox = Turf.bbox(feature);
      this.map.fitBounds(bbox);

      if (this.map.getLayer("drawLine")) {
        this.map.removeLayer("drawLine")
      }
      if (this.map.getSource("drawLine")) {
        this.map.removeSource("drawLine")
      }
      this.map.addLayer({
        id: "drawLine",
        type: "line",
        layout: {},
        paint: {
          "line-color": "#FF1493",
          "line-width": 5
        },
        "source": {
          "type": "geojson",
          "data": feature
        }
      })
    },
    mapDrag() {
      this.curLng = this.map.getCenter().lng.toFixed(6);
      this.curLat = this.map.getCenter().lat.toFixed(6);
    },
    mapZoomEnd() {
      this.curLevel = this.map.getZoom().toFixed(2);
      this.curLng = this.map.getCenter().lng.toFixed(6);
      this.curLat = this.map.getCenter().lat.toFixed(6);
      //更新中心点落入的行政区划信息
      this.calCenterAdminArea()
    },
    mapMoveEnd: function () {
      //更新中心点落入的行政区划信息
      this.calCenterAdminArea()
    },
    calCenterAdminArea() {
      let map = this.map;
      let centPt = map.project(map.getCenter());

      let features = map.queryRenderedFeatures(centPt); //查询点击的要素

      let tempLvl = 6; /*一共六个级别*/
      let resLevel = -1;
      let res = null; /*最终结果*/

      features.forEach((feature) => {
        /*查找当前遍历元素对应的配置数据*/
        //定义下钻图层配置
        let lyrDrl = layer_identify.layer_Drilldown.find((lyr) => {
          return feature.layer.source === lyr.sourceId;
        });

        if (lyrDrl && lyrDrl.level <= tempLvl) {
          resLevel = lyrDrl.level;
          res = feature;
        }
      });

      this.curAreaName = res ? res.properties.qhmc : "";
    },
    getYzInfo(a) {
      let that = this
      that.infoMarkers && that.infoMarkers.forEach(item => {
        item.remove();
      })
      // let featureCollection = Turf.featureCollection(this.a);
      //---- 地块数据处理 ----
      let yzInfoArr = []
      let rawData = []

      this.yzInfo.forEach(item => {
        yzInfoArr.push(JSON.parse(item[0].shape1))

        //----------- 坐标和名称
        rawData.push({coordinate: item[0].coordinate, xnzt: item[0].xnzt})
      })


      if (yzInfoArr) {
        if (yzInfoArr.length === 1) {
          let feature = Turf.feature(yzInfoArr[0]);
          let bbox = Turf.bbox(feature);
          this.map.fitBounds(bbox, {padding: 100});

          if (this.map.getLayer("getYzInfo")) {
            this.map.removeLayer("getYzInfo")
          }
          if (this.map.getSource("getYzInfo")) {
            this.map.removeSource("getYzInfo")
          }

          this.map.addLayer({
            id: "getYzInfo",
            type: "line",
            layout: {},
            paint: {
              "line-color": "#1B1FE3",
              "line-width": 5,
            },
            source: {
              "type": "geojson",
              "data": feature
            },
          })
        } else if (yzInfoArr.length > 1) {
          let featureCollection = Turf.featureCollection(yzInfoArr);
          let bbox = Turf.bbox(featureCollection);
          this.map.fitBounds(bbox, {padding: 100});
          if (this.map.getLayer("getYzInfo")) {
            this.map.removeLayer("getYzInfo")
          }
          if (this.map.getSource("getYzInfo")) {
            this.map.removeSource("getYzInfo")
          }
          this.map.addLayer({
            id: "getYzInfo",
            type: "line",
            layout: {},
            paint: {
              "line-color": "#1B1FE3",
              "line-width": 5,
            },
            source: {
              "type": "geojson",
              "data": featureCollection
            },
          })
        }

        rawData.forEach(ils => {
          let coords = JSON.parse(ils.coordinate)
          let es = ils.xnzt
          let popupHtml = "<div style='width: 150px;'><div style='text-align:center;font-weight:bold;font-size: 16px'>"
            + "<span>" + es + "</span>"
            + "</div></div>";
          let popupOffsets = {//定义统计标签弹出窗口偏移量
            'top': [0, 0],//向下显示，越正越往下
            'left': [20, 0],
            'bottom': [0, 0],
          };

          new mapboxgl.Popup({offset: popupOffsets, anchor: 'left', closeButton: false})
            .setLngLat(coords)
            .setHTML(popupHtml)
            .addTo(this.map);
        })
      }
    },
    saveQhdm() {
      //暂存区划代码
      this.newPathData && this.newPathData.qhdm && localStorage.setItem('saveLocalQhdm', this.qhdm)
      console.log('goback')
    },

    clearMarkers() {
      for (let i = 0; i < this.rediconMarkers.length; i++) {
        this.rediconMarkers[i].remove()
      }
    },

    getTolocation(dkList) {
      this.clearMarkers()
      for (let i = 0, l = dkList.length; i < l; i++) {
        //添加定位图标marker并存储
        let icon = document.createElement('div');
        icon.className = 'icon';
        icon.style.width = '28px';
        icon.style.height = '33px';
        icon.style.background = "none";
        icon.style.backgroundImage = this.redIcon;

        let nh = dkList[i]
        if (!nh.shape) {
          continue
        }
        // let points = Turf.feature(nh.shape)

        let point = JSON.parse(nh.shape)
        if (!point.coordinates) {
          continue
        }
        //是否有定位小图标
        let iconMarker = new mapboxgl.Marker(icon, {offset: [-14, -33]})
          .setLngLat(point.coordinates)
          .addTo(this.map);
        this.rediconMarkers.push(iconMarker)

        //添加面积标签marker并存储
        let el = document.createElement('div');
        el.className = 'xdk-marker';
        el.style.padding = '3px 10px';
        el.innerHTML = nh.mj + '亩'
        let infoMarker = new mapboxgl.Marker(el, {offset: [20, -55]})
          .setLngLat(point.coordinates)
          .addTo(this.map)
        this.rediconMarkers.push(infoMarker)
      }

      let featureArr = [];
      for (let i = 0; i < dkList.length; i++) {
        featureArr.push(Turf.feature(JSON.parse(dkList[i].shape)));
      }
      let featureCollection = Turf.featureCollection(featureArr);
      let center = Turf.center(featureCollection);
      let bbox = Turf.bbox(featureCollection);
      this.map.setCenter(center.geometry.coordinates);
      this.map.fitBounds(bbox);
    },
  }
}
</script>

<style scoped>
@import url('https://api.tiles.mapbox.com/mapbox-gl-js/v1.1.1/mapbox-gl.css');

#map {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
}

.parent {
  width: 100%;
  height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
}

.zoom-info {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 1;
  font-size: 12px;
  height: 24px;
  text-align: center;
}

.zoom-info div {
  width: 180px;
  border-right: 2px solid #fff;
  text-align: center;
  height: 14px;
  margin: 5px 0;
  display: inline-block;
}

.zoom-info div:last-child {
  border: none;
}

.zoom-info div span {
  color: #fff;
  position: relative;
  top: -3px;
}

.zoom-info div span {
  vertical-align: middle;
}

</style>
<style lang="scss">
.xdk-marker {
  color: #fff;
  padding: 3px 10px !important;
  background-color: #101A64 !important;

}

//.mDialog{
//  background: #101A64 !important;
//  color: white !important;
//  .el-dialog__title{
//    color: white !important;
//  }
//  .el-table {
//    tr{
//      background: #101A64 !important;
//      color: white !important;
//    }
//    th.el-table__cell{
//      background: #101A64 !important;
//      color: white !important;
//    }
//  }
//}
.areaInput{
  input::placeholder{
    color: #606266 !important;
  }
  //修改placeholder的默认颜色：
  input::-webkit-input-placeholder{
    color: #606266 !important;
  }
  input::-moz-placeholder{   /* Mozilla Firefox 19+ */
    color: #606266 !important;
  }
  input:-moz-placeholder{    /* Mozilla Firefox 4 to 18 */
    color: #606266 !important;
  }
  input:-ms-input-placeholder{  /* Internet Explorer 10-11 */
    color: #606266 !important;
  }
}


</style>
